#encoding: utf-8

from apps.forms import BaseForm
from wtforms import StringField
from wtforms.validators import regexp,InputRequired
import hashlib
#(new Date).getTime()  13位
class SMSCaptchaForm(BaseForm):
    salt = '12qwertyuiopasdfghjklzxcvbnm,.!@#@!#'
    telephone = StringField(validators=[regexp(r'1[345789]\d{9}')])
    timestamp = StringField(validators=[regexp(r'\d{13}')])
    sign = StringField(validators=[InputRequired()])

    def validate(self):
        result = super(SMSCaptchaForm, self).validate()
        if not result:
            return False

        telephone = self.telephone.data
        print(telephone)
        timestamp = self.timestamp.data
        print(timestamp)
        sign = self.sign.data #用户提交过来的

        # md5(timestamp+telphone+salt)
        # md5函数必须要传一个bytes类型的字符串进去
        #hashlib.md5((timestamp+telephone+self.salt).encode('utf-8'))这是对象
        #如果跟前端进行比较  必须转成字符串  hexdigest 生成字符串
        # sign2 = hashlib.md5((timestamp+telephone+self.salt).encode('utf-8')).hexdigest()
        sign2 = hashlib.md5((timestamp+telephone+self.salt).encode('utf-8')).hexdigest()

        print('客户端提交的sign：',sign)
        print('服务器生成的sign：',sign2)
        if sign == sign2:
            return True
        else:
            return False
